package com.cin.cma.client.service.impl;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.StopWatch;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONObject;
import com.cin.cma.client.service.ICallbackService;
import com.cin.cma.client.service.IHttpService;
import com.cin.cma.common.model.SocketRequest;
import com.cin.cma.common.model.SocketResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.function.Function;

@Slf4j
@Service
public class HttpServiceImpl implements IHttpService {

    @Value("${proxy.host}")
    private String proxyHost;
    @Value("${proxy.port}")
    private int proxyPort;
    @Autowired
    private ICallbackService callbackService;

    /**
     * 请求数据
     *
     * @param url  请求路径
     * @param body 请求内容
     * @return 返回内容
     */
    @Override
    public SocketResponse request(String url, String body, Function<SocketRequest, HttpResponse> callback) {
        SocketRequest socketRequest = JSONObject.parseObject(body, SocketRequest.class);
        if (StrUtil.isBlank(url) && StrUtil.isBlank(socketRequest.getRequestUrl())) {
            SocketResponse socketResponse = new SocketResponse();
            socketResponse.setResponseBody("请求地址错误");
            socketResponse.setHttpStatus(500);
            socketResponse.setRequestDuration(1);
            socketResponse.setRequestId(socketRequest.getRequestId());
            socketResponse.setResponseTime(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
            this.callbackService.send(socketRequest, socketResponse);
            return socketResponse;
        }
        if (StrUtil.isBlank(socketRequest.getRequestUrl())) {
            socketRequest.setRequestUrl(StrUtil.format("http://{}:{}/{}", proxyHost, proxyPort, url));
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        int httpStatus;
        String responseBody;
        try {
            HttpResponse response = callback.apply(socketRequest);
            httpStatus = response.getStatus();
            responseBody = response.body();
        } catch (Exception e) {
            httpStatus = -1;
            responseBody = null;
            log.error("网络请求失败,url={},body={}", url, body, e);
        }
        stopWatch.stop();
        SocketResponse socketResponse = new SocketResponse();
        socketResponse.setResponseBody(responseBody);
        socketResponse.setHttpStatus(httpStatus);
        socketResponse.setRequestDuration(stopWatch.getTotalTimeMillis());
        socketResponse.setRequestId(socketRequest.getRequestId());
        socketResponse.setResponseTime(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
//        String logInfo = StrUtil.format("请求ID：{}\r\n请求地址：{}\r\n请求参数：{}\r\n请求耗时：{}\r\n返回状态：{}\r\n返回结果：{}",
//                socketRequest.getRequestId(), socketRequest.getRequestUrl(), socketRequest.getRequestBody(), stopWatch.getTotalTimeMillis(), httpStatus, responseBody);
//        log.info(logInfo);
        this.callbackService.send(socketRequest, socketResponse);
        return socketResponse;
    }

    /**
     * 请求数据
     *
     * @param body 请求内容
     * @return 返回内容
     */
    @Override
    public SocketResponse request(String body, Function<SocketRequest, HttpResponse> callback) {
        return this.request(null, body, callback);
    }
}
